package com.p2p.wallet.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.annotation.Resource;

import org.apache.commons.httpclient.HttpClient;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.IService;
import com.p2p.account.po.Account;
import com.p2p.common.base.BaseServiceImpl;
import com.p2p.common.redis.RedisService;
import com.p2p.common.redis.vo.RedisVo;
import com.p2p.user.mapper.PermissionMapper;
import com.p2p.user.po.Permission;
import com.p2p.user.vo.PermissionVo;
import com.p2p.wallet.mapper.WalletMapper;
import com.p2p.wallet.po.Wallet;
import com.p2p.wallet.service.CoinStartService;
import com.p2p.wallet.service.WalletService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.baomidou.mybatisplus.service.IService;

@Service
public class CoinStartServiceImpl implements CoinStartService {
	@Resource(name = "redisService")
	private RedisService<RedisVo> redisService;
	@Resource(name = "redisTemplate")
	protected RedisTemplate<String, String> redisTemplate;

	@Override
	public Map Getcoin() {

		return null;
	}

	public Map getHTMLUrls() {

		try {

			TreeMap<String, String> map = new TreeMap<String, String>();
			NodeList nodeList = null;
			HttpClient client = new HttpClient();

			NodeFilter filter = new TagNameFilter("a");

			Parser parser = new Parser("https://coinmarketcap.com/");
			client.getHttpConnectionManager().getParams().setConnectionTimeout(3000);
			parser.setEncoding("utf-8");

			nodeList = parser.parse(filter);
			// System.out.println(nodeList.asString());

			String str1[] = nodeList.asString().split("\n");
			Date date = new Date();
			Date date1 = new Date(date.getTime() - 60 * 60 * 1000);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
			String str = format.format(date1);
			List<RedisVo> list = new ArrayList<RedisVo>();
			System.out.println(str1.length);
			for (int i = 0; i < str1.length; i++) {
				if (str1[i].indexOf("$") > -1) {
					if (str1[i].substring(0, 3).equals("ZEC") || str1[i].substring(0, 3).equals("XZC")) {
						int location = str1[i].indexOf("$");
						RedisVo secret = new RedisVo(str1[i].substring(0, 3),
								str1[i].substring(location + 1, str1[i].indexOf("$", (location + 1))));
						Map<String, Object> testMap = new HashMap();

						redisTemplate.opsForHash().put(str1[i].substring(0, 3) + ":" + str, "price",
								str1[i].substring(location + 1, str1[i].indexOf("$", (location + 1))));
						;
						// System.out.println(redisTemplate.opsForHash().entries(str1[i].substring(0,
						// 3)).get("price"));
						map.put(str1[i].substring(0, 3),
								str1[i].substring(location + 1, str1[i].indexOf("$", (location + 1))));
					}
				}

			}

			return map;

		} catch (ParserException ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public String JDKFetch(String request, String charset) throws Exception {
		URL url = new URL(request);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 模拟浏览器参数
		conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36"
				+ " (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			InputStream input = conn.getInputStream();
			StringBuffer sb = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(input, charset));
			String s;
			while ((s = reader.readLine()) != null) {
				sb.append(s + "\n");
			}
			input.close();
			conn.disconnect();

			return sb.toString();
		}
		return "";
	}

	public void PutCoin(String WalletPool, String charset, String type) throws Exception {

		try {
			String urlmessage = this.JDKFetch("https://api-zcash.flypool.org/miner/" + WalletPool + "/dashboard",
					charset);

			JSONObject json = JSONObject.fromObject(urlmessage);
			// json =
			// JSONObject.fromObject(json.getString("currentStatistics"));
			Date date = new Date();
			Date date1 = new Date(date.getTime() - 60 * 60 * 1000);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
			String str = format.format(date1);
			json = (JSONObject) json.get("data");

			json = (JSONObject) json.get("currentStatistics");

			redisTemplate.opsForHash().put(type + ":" + str, "currentHashrate",
					String.valueOf(Float.valueOf(json.get("currentHashrate").toString()) / 1000));

			redisTemplate.opsForHash().put(type + ":" + str, "unpaid", json.get("unpaid").toString());

			PutCoinCount(WalletPool, charset, type);
		} catch (Exception e) {

			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void PutCoinCount(String WalletPool, String charset, String type) throws Exception {
		try {
			String urlmessage = JDKFetch("https://api-zcash.flypool.org/miner/" + WalletPool + "/dashboard/payouts",
					charset);

			JSONObject json = JSONObject.fromObject(urlmessage);
			// json =
			// JSONObject.fromObject(json.getString("currentStatistics"));

			json = (JSONObject) json.get("data");

			JSONArray jsonarray = (JSONArray) json.get("payouts");
			Date date = new Date();
			Date date1 = new Date(date.getTime() - 60 * 60 * 1000);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
			String str = format.format(date1);
			String nstr = format.format(date);
			int coincount = 0;
			int ycoincount = 0;
			System.out.println(
					redisTemplate.opsForHash().entries(type + ":" + str).size());
			if (redisTemplate.opsForHash().entries(type + ":" + str).size() > 0) {

				coincount = Integer.valueOf(
						(redisTemplate.opsForHash().entries(type + ":" + str).get("unpaid"))
								.toString());

			}

			if (redisTemplate.opsForHash().entries(type + ":" + nstr).size() > 0) {

				ycoincount = Integer.valueOf((redisTemplate.opsForHash()
						.entries(type + ":" + nstr).get("unpaid"))
								.toString());

			}

			for (int i = 0; i < jsonarray.size(); i++) {
				JSONObject json1 = (JSONObject) jsonarray.get(i);
				if (str.substring(8, 10).replaceAll("-", "").toString()
						.equals(transForDate(Integer.valueOf(json1.get("paidOn").toString())).substring(8, 10)
								.replaceAll("-", "").toString())) {
					System.out.println(transForDate(Integer.valueOf(json1.get("paidOn").toString())).substring(8, 10)
							.replaceAll("-", ""));
					coincount = coincount + Integer.valueOf(json1.get("amount").toString());
				}

			}
			int count = coincount - ycoincount;
			redisTemplate.opsForHash().put(type + ":" + str, "count", String.valueOf((float) count / 100000000));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String transForDate(Integer ms) throws java.text.ParseException {
		if (ms == null) {
			ms = 0;
		}
		long msl = (long) ms * 1000;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:00:00");
		Date temp = null;
		String str = null;
		if (ms != null) {

			str = sdf.format(msl);

		}
		return str;
	}

}